import { UserService } from 'src/service/user/user.service';
import { ResponseInterceptor } from 'src/interceptor/response/response.interceptor';
import { AddressService } from 'src/service/address/address.service';
import { Body, Controller, Get, Post, Req, UseInterceptors, BadRequestException, Delete, Patch } from '@nestjs/common';
import config from 'src/config/config';

@UseInterceptors(ResponseInterceptor)
@Controller(`${config.shopApiPath}/address`)
export class AddressController {
    constructor(private readonly addressService: AddressService, private readonly userService: UserService) {}
    @Get()
    async getAddress(@Req() req) {
        const { _id: uid } = await this.userService.getUser(req);
        let list = await this.addressService.find({ uid });
        const defaultNum = list.reduce((pre, item) => (item.default_address === 1 ? ++pre : pre), 0);
        if (list.length && defaultNum !== 1) {
            if (defaultNum === 0) {
                const { _id } = list[0];
                await this.addressService.getModel().updateOne({ _id }, { default_address: 1 });
            } else if (defaultNum > 1) {
                const { uid, _id } = list[0];
                await this.addressService.getModel().updateMany({ uid }, { default_address: 0 });
                await this.addressService.getModel().updateOne({ _id }, { default_address: 1 });
            }
            list = await this.addressService.find({ uid });
        }
        return list;
    }
    @Post()
    async create(@Body() body, @Req() req) {
        const { name, phone, address, zipcode = '000000', default_address = 0 } = body;
        const { _id: uid } = await this.userService.getUser(req);
        if (!name || !phone || !address) throw new BadRequestException('请输入必填表单域');
        if (!config.phonePattern.test(phone)) throw new BadRequestException('手机号格式不符');
        this.addressService.create({ uid, name, phone, address, zipcode, default_address });
    }
    @Patch()
    async updateAddress(@Body() body) {
        return await this.addressService.update(body);
    }
    @Patch('changeDefaultAddress')
    async changeDefaultAddress(@Req() req, @Body() body) {
        const { _id: uid } = await this.userService.getUser(req);
        const { _id } = body;
        await this.addressService.getModel().updateMany({ uid }, { default_address: 0 });
        await this.addressService.getModel().update({ _id }, { default_address: 1 });
        return;
    }
    @Delete()
    async deleteAddress(@Body() body) {
        return await this.addressService.delete(body);
    }
}
